<template>
  <div class="level-adjustment">
    <el-card>
      <div slot="header">
        <span>调级管理</span>
      </div>

      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="部门" v-if="userRole === 2">
          <el-select v-model="queryForm.departmentId" placeholder="请选择部门" clearable @change="handleQuery">
            <el-option
                v-for="dept in departments"
                :key="dept.departmentId"
                :label="dept.departmentName"
                :value="dept.departmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 员工列表 -->
      <el-table :data="employeeList" border style="width: 100%">
        <el-table-column prop="employeeName" label="员工姓名" width="120"></el-table-column>
        <el-table-column prop="employeeNo" label="员工号" width="120"></el-table-column>
        <el-table-column prop="currentSalaryLevel" label="当前薪资级别" width="150"></el-table-column>
        <el-table-column prop="departmentName" label="部门名称" width="150"></el-table-column>
        <el-table-column prop="position" label="角色" width="120"></el-table-column>
        <el-table-column label="薪资级别" width="200">
          <template slot-scope="scope">
            <el-select
                v-model="scope.row.newLevelId"
                placeholder="请选择薪资级别"
                clearable
                :key="'salaryLevelSelect' + scope.$index"
            >
              <el-option
                  v-for="level in salaryLevels"
                  :key="level.salaryLevelId"
                  :label="level.salaryLevelName"
                  :value="level.salaryLevelId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                @click="handleAdjust(scope.row)"
                :disabled="!scope.row.newLevelId || scope.row.newLevelId === scope.row.currentLevelId"
            >
              调级
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 错误提示 -->
    <el-dialog title="错误" :visible.sync="errorDialogVisible" width="30%">
      <span>{{ errorMessage }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="errorDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAdjustableEmployees, adjustLevel } from '@/api/levelAdjustment';
import { getAllDepartments } from '@/api/departmentApi';
import { getSalaryLevels } from '@/api/salary';
import Vue from 'vue';
import axios from 'axios';

Vue.prototype.$axios = axios;

export default {
  name: 'LevelAdjustment',
  data() {
    return {
      queryForm: {
        departmentId: null
      },
      employeeList: [],
      departments: [],
      salaryLevels: [],
      userId: 1,
      userRole: 2,
      errorDialogVisible: false,
      errorMessage: ''
    };
  },
  created() {
    this.fetchSalaryLevels();
    if (this.userRole === 2) {
      this.fetchDepartments();
    }
    this.fetchEmployees();
  },
  methods: {
    fetchSalaryLevels() {
      getSalaryLevels()
          .then(response => {
            console.log('【原始响应】薪资级别:', response);

            // 检查 response.data 是否是对象，并从中提取真正的数据
            const rawData = response.data;

            if (rawData && Array.isArray(rawData.data)) {
              // 假设实际数据在 rawData.data 中
              this.salaryLevels = rawData.data.map(level => ({
                salaryLevelId: Number(level.salaryLevelId),
                salaryLevelName: level.salaryLevelName || '未知级别',
                baseSalary: level.baseSalary,
                annualSalaryDays: level.annualSalaryDays,
                maxConsecutiveVacationDays: level.maxConsecutiveVacationDays
              }));
              console.log('【处理后】薪资级别:', this.salaryLevels);
            } else {
              console.warn('【警告】薪资级别数据格式不正确', rawData);
              this.salaryLevels = [];
            }
          })
          .catch(error => {
            console.error('获取薪资级别失败:', error);
          });
    },

    fetchDepartments() {
      getAllDepartments()
          .then(response => {
            if (response.data) {
              this.departments = response.data;
              console.log('Departments:', this.departments);
            } else {
              console.error('无法获取部门数据:', response);
            }
          })
          .catch(error => {
            console.error('Error fetching departments', error);
          });
    },

    async fetchEmployees() {
      try {
        const userId = window.sessionStorage.getItem('empId');
        const userRole = window.sessionStorage.getItem('role');

        if (!userId || !userRole) {
          this.$message.error('无法获取当前用户信息，请重新登录');
          return;
        }

        let departmentId = null;

        // 普通员工只允许看本部门
        if (Number(userRole) === 1) {
          const response = await this.$axios.get(`http://localhost:8082/employee/queryEmpInfoById/${userId}`, {
            withCredentials: true
          });
          const userInfo = response.data.data;
          departmentId = userInfo.departmentId;
        }

        // 管理员：从查询表单中获取选中的部门
        if (Number(userRole) === 2) {
          if (!this.queryForm.departmentId) {
            this.$message.warning('请选择部门');
            return;
          }
          departmentId = Number(this.queryForm.departmentId);
        }

        // 请求后端接口获取员工数据
        const empResponse = await getAdjustableEmployees(departmentId, userId, userRole);
        console.log(empResponse);
        if (!empResponse || !Array.isArray(empResponse.data)) {
          throw new Error('员工列表数据格式错误');
        }

        this.employeeList = empResponse.data.map(emp => ({
          ...emp,
          newLevelId: null
        }));
      } catch (error) {
        console.error('获取员工列表失败:', error);
        this.$message.error(`获取员工列表失败: ${error.response?.data?.message || error.message || '未知错误'}`);
        this.employeeList = [];
      }
    },

    handleQuery() {
      if (this.queryForm.page) {
        this.queryForm.page = 1;
      }
      this.fetchEmployees();
    },

    handleAdjust(row) {
      // 如果新等级为空 或 新旧等级相同，则不执行调级
      if (!row.newLevelId || row.newLevelId === row.currentLevelId) {
        return;
      }
      console.log('即将调级的员工ID:', row.employeeId);
      console.log('目标薪资等级:', row.newLevelId);
      // 从 sessionStorage 中获取用户信息（必须为整数类型）
      const userId = window.sessionStorage.getItem('empId');
      const userRole = window.sessionStorage.getItem('role');

      // 检查用户是否登录
      if (!userId || !userRole) {
        this.$message.error('用户未登录或权限不足');
        return;
      }

      // 构造请求参数
      const params = {
        employeeId: row.employeeId,
        newSalaryLevel: row.newLevelId,   // ✅ 改成 newSalaryLevel
        remark: ''                        // 可选：如果后端要求非空，建议加上
      };

      // 调用接口，注意将 userId 和 userRole 转为整数
      adjustLevel(params, parseInt(userId), parseInt(userRole))
          .then(() => {
            this.$message.success('调级成功');
            this.fetchEmployees(); // 刷新员工列表
          })
          .catch(error => {
            console.error('调级失败', error);
            this.errorMessage = error.message || '调级失败';
            this.errorDialogVisible = true;
          });
    }
  }
};
</script>

<style scoped>
.level-adjustment {
  padding: 20px;
}
</style>